package parser;

import antlr.RecognitionException;
import antlr.Token;
import java.util.*;

class Tuple extends Expr {
    
    List<Expr> members;
    
    Tuple(List<Expr> members) {
        this.members = members;
    }
  
    void write(ByteStream out) throws RecognitionException {
        for (Expr e : members) {
            e.write(out);
        }
        out.write(Opcodes.PACK);
        out.write(members.size());
    }
    
    void tuple_parameter(ByteStream out) throws RecognitionException {
        write(out);
    }

    void delete(ByteStream out) throws RecognitionException {
        throw new RecognitionException("Cannot delete rvalue");
    }
    
    void writeLHS(ByteStream out) throws RecognitionException {
        unpack(members, out);
    }
    
    static void unpack(List<Expr> members, ByteStream out) throws RecognitionException {
        out.write(Opcodes.SEQUENCE_TO_LIST_OR_TUPLE);
        out.write(Opcodes.UNPACK);
        int size = members.size();
        out.write(size);
        for (Expr e: members) {
            e.writeLHS(out);
        }
    }

    void lhs() throws RecognitionException {
        for (Expr e : members)
            e.lhs();
    }
    
    Stmt assign(Expr rhs) throws RecognitionException {
        lhs();
        if (rhs instanceof Tuple) {
            if (((Tuple)rhs).members.size() != members.size()) {
                   throw new RecognitionException("Unbalanced number of items in multiple assignment");
            } else {
                return new MultAsgnStmt(members, ((Tuple)rhs).members);
            }
        } else {
            return new AsgnStmt(this, rhs);   
        }
    }
}
